437B - The Child and Set - CodeForces Solution


bitmasks greedy implementation sortings *1500

Please click on ads to support us..

Python Code:

from collections import defaultdict, deque
from functools import lru_cache
from heapq import heappush, heappop
from bisect import bisect_right, bisect_left
from fractions import Fraction as frac
import math
hpop = heappop
hpush = heappush
MOD = 10**9 + 7

def solution():
    
        sum_, limit = map(int, input().split())
    first_bit_map = defaultdict(list) 
    for num in range(1, limit+1):
        first_bit = num & -num
        first_bit_map[first_bit].append(num)
    first_bits = list(sorted(first_bit_map.keys(), reverse=True))
    
    res = []
    i = 0
    while i < len(first_bits) and sum_:
        val = first_bits[i]

        if val > sum_ or len(first_bit_map[val]) == 0:
            i += 1
            continue

        sum_ -= val 
        p = first_bit_map[val].pop()
        res.append(p)

    if sum_ > 0:
        return print(-1)

    print(len(res))
    return print(" ".join(map(str, res)))
            
def main():
    t = 1
        for _ in range(t):
        solution() 
 
main()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
vector<ll> V;
int main()
{ll s,l,i;
cin>>s>>l;
for(i=l;i>0&&s>0;i--)
if(s-(i&-i)>=0)
{s-=(i&-i);
V.push_back(i);}
 
if(s!=0)
cout<<-1;
else
{cout<<V.size()<<endl;
for(i=0;i<V.size();i++)
cout<<V[i]<<" ";}
return 0;
}


Comments

Submit
0 Comments
More Questions

1651E - Sum of Matchings
19A - World Football Cup
630P - Area of a Star
1030C - Vasya and Golden Ticket
1529D - Kavi on Pairing Duty
1743A - Password
1743B - Permutation Value
1743C - Save the Magazines
1743D - Problem with Random Tests
1070K - Video Posts
767C - Garland
1201B - Zero Array
1584C - Two Arrays
1131C - Birthday
1285B - Just Eat It
1743F - Intersection and Union
771A - Bear and Friendship Condition
1208E - Let Them Slide
656A - Da Vinci Powers
1025A - Doggo Recoloring
257A - Sockets
231C - To Add or Not to Add
1454E - Number of Simple Paths
931B - World Cup
934B - A Prosperous Lot
999B - Reversing Encryption
1238D - AB-string
810B - Summer sell-off
84A - Toy Army
185A - Plant